package com.kongjs.common.datasource.component;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Component
public class DynamicDataSourceRegistrar {

    @Resource
    private ConfigurableListableBeanFactory beanFactory;

    public DataSource registerDataSource(String beanName, DataSource dataSource) {
        // 将 ConfigurableListableBeanFactory 转换为 DefaultListableBeanFactory
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory;
        // 创建一个通用的 Bean 定义
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        // 设置 Bean 的类类型
        beanDefinition.setBeanClass(dataSource.getClass());
        // 设置 Bean 的实例
        beanDefinition.setInstanceSupplier(() -> dataSource);
        // 注册 Bean 到 Bean 工厂
        defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinition);
        // 返回 Bean
        return defaultListableBeanFactory.getBean(beanName, DataSource.class);
    }
}
